﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AgriMarketWebProj.AgriMarketService;
using System.Configuration;
using AgriMarketWebProj.Models;
using System.Web.Script.Serialization;
using System.IO;
namespace AgriMarketWebProj.Controllers
{
    public class AuctionController : Controller
    {
        //
        // GET: /Auction/
        public ActionResult CheckLogIn_Require()
        {
            AgriMarketWebService service = new AgriMarketWebService();
            UserAccount userAccount = null;
            if (Session["CurrentUserAccount"] != null)
            {
                userAccount = service.GetUserAccountByUserName(Session["CurrentUserAccount"].ToString());
                ViewBag.CurrentUserAccount = userAccount;
                if (userAccount.TypeOfUser.TypeId != AdminCode.AdminTypeCode)
                    return Content("Bạn không có quyền truy cập!");
                return null;
            }
            else
            {
                TempData["ReturnUrl"] = Request.Url.PathAndQuery;
                return RedirectToAction("LogIn", "UserAccount");
            }
        }
        public void CheckLogIn_NoRequire()
        {
            AgriMarketWebService service = new AgriMarketWebService();
            UserAccount userAccount = null;
            if (Session["CurrentUserAccount"] != null)
            {
                userAccount = service.GetUserAccountByUserName(Session["CurrentUserAccount"].ToString());
                ViewBag.CurrentUserAccount = userAccount;
            }
        }
        public ActionResult Index()
        {
            AgriMarketWebService service = new AgriMarketWebService();
            CheckLogIn_NoRequire();
            List<Auction> newUnfinishedAuctions = service.GetNNewUnfinishedAuctions(10).ToList();
            ViewBag.NewUnfinishedAuctions = newUnfinishedAuctions;
            ViewBag.AllProducts = service.GetAllProducts().ToList();
            ViewBag.TypeId = 3;//auction
            ViewBag.TypeView = 1;//all auction
            return View("AuctionIndex");
        }

        public ActionResult LoadNextAuctions(int startedId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            List<Auction> newUnfinishedAuctions = service.GetNNextUnfinishedAuctions(startedId, 4, true).ToList();
            CheckLogIn_NoRequire();
            if (Request.IsAjaxRequest())
            {
                if (newUnfinishedAuctions.Count > 0)
                    return Json(new { lastId = newUnfinishedAuctions[newUnfinishedAuctions.Count - 1].AuctionId, content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", newUnfinishedAuctions) });
                else
                    return Json(new { lastId = -1, content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", newUnfinishedAuctions) });
            }
            return PartialView("ListAuctionsView", newUnfinishedAuctions);

        }

        public ViewResult BeingAuctions()
        {
            AgriMarketWebService service = new AgriMarketWebService();
            CheckLogIn_NoRequire();
            List<Auction> beingAuctions = service.GetNFirstBeingAuctions(10).ToList();
            ViewBag.NewUnfinishedAuctions = beingAuctions;
            ViewBag.AllProducts = service.GetAllProducts().ToList();
            ViewBag.TypeId = 3;//buy
            ViewBag.TypeView = 2;// being auction
            return View("AuctionIndex");
        }

        [HttpPost]
        public ActionResult LoadNextBeingAuctions(int startedId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            List<Auction> beingAuctions = service.GetNNextBeingAuctions(startedId, 5, true).ToList();
            CheckLogIn_NoRequire();
            if (Request.IsAjaxRequest())
            {
                if (beingAuctions.Count > 0)
                    return Json(new { lastId = beingAuctions[beingAuctions.Count - 1].AuctionId, content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", beingAuctions) });
                else
                    return Json(new { lastId = -1, content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", beingAuctions) });
            }
            return PartialView("ListAuctionsView", beingAuctions);
        }

        public ActionResult ViewBuyAuctionIndex()
        {
            AgriMarketWebService service = new AgriMarketWebService();
            CheckLogIn_NoRequire();
            List<Auction> newUnfinishedAuctions = service.GetNNewUnFinishedBuyAuctions(10).ToList();
            ViewBag.NewUnfinishedAuctions = newUnfinishedAuctions;
            ViewBag.AllProducts = service.GetAllProducts().ToList();
            ViewBag.TypeId = 1;//buy auction
            ViewBag.TypeView = 1;//all auction
            return View("AuctionIndex");
        }

        public ViewResult ViewAuction(Auction auction)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            CheckLogIn_NoRequire();
            ViewBag.AuctioneerList = service.GetNNNewAuctioneers(auction.AuctionId, 3).ToList();
            return View("AuctionView",auction);
        }
        [HttpPost]
        public ActionResult LoadNextBuyAuctions(int startedId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            List<Auction> newUnfinishedBuyAuctions = service.GetNUnfinishedBuyAuctions(startedId, 4, true).ToList();
            CheckLogIn_NoRequire();
            if (Request.IsAjaxRequest())
            {
                if (newUnfinishedBuyAuctions.Count > 0)
                    return Json(new { lastId = newUnfinishedBuyAuctions[newUnfinishedBuyAuctions.Count - 1].AuctionId, content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", newUnfinishedBuyAuctions) });
                else
                    return Json(new { lastId = -1, content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", newUnfinishedBuyAuctions) });
            }
            return PartialView("ListAuctionsView", newUnfinishedBuyAuctions);
            
        }
        [HttpPost]
        public JsonResult UpdateAuction(Auction updatedAuction)
        {
            
            string errorMessage = "";
            bool ok = true;
            int state = -1;
            if (updatedAuction.InitialPrice <= 0) {
                errorMessage += "Giá khởi điểm không hợp lệ<br/>";
                ok = false;
            }
            if (updatedAuction.StartedDate < DateTime.Today.AddDays(1))
            {
                errorMessage += "Thời điểm bắt đầu phải cách thời gian đăng ít nhất 1 ngày<br/>";
                ok = false;
            }
            if(updatedAuction.StartedDate>=updatedAuction.FinishedDate){
                errorMessage += "Thời gian kết thúc phải sau thời gian bắt đầu<br/>";
                ok = false;
            }
            if (ok)
            {
                AgriMarketWebService service = new AgriMarketWebService();
                state= service.UpdateAuction(updatedAuction);
                if (state == 0) {
                    errorMessage = "Thành công";
                }
            }
            return Json(new { IsOk =state, ErrorMessage = errorMessage });
        }
        [HttpPost]
        public JsonResult DeleteAuction(int auctionId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            return Json(new { IsOk = service.DeleteAuction(auctionId) });
        }
        [HttpPost]
        public string UploadImage(string updatedAuctionJson, HttpPostedFileBase image)
        {
            if (image != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                Auction updatedAuction = (Auction)serializer.Deserialize(updatedAuctionJson, typeof(Auction));

                AgriMarketWebService service = new AgriMarketWebService();
                string type = image.FileName.Split('.')[1];
                byte[] imageBytes = new byte[image.ContentLength];
                image.InputStream.Read(imageBytes, 0, image.ContentLength);
                updatedAuction.ProductImageBytes = imageBytes;
                service.UpdateAuction(updatedAuction);
                return ServiceURL.ServicePath+ updatedAuction.ProductImage;
            }
            else
            {
                return "1";
            }
        }
        public ActionResult GetNAuctioneers(int auctionId, int n, bool isOld)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            List<Auctioneer> auctioneers = service.GetNNNewAuctioneers(auctionId, n).ToList();
            return View("AuctioneersList", auctioneers);
        }
        #region Ajax For AuctionView
        [HttpPost]
        public JsonResult LoadPreviousAuctioneers(int auctionId,int startedId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            List<Auctioneer> previousAuctioneers = service.GetNNextAuctioneers(auctionId, startedId, 3, false).ToList();
            if (Request.IsAjaxRequest())
            {
                if (previousAuctioneers.Count > 0)
                    return Json(new { previousLastId = previousAuctioneers[previousAuctioneers.Count - 1].AuctioneerId, content = Helper.RenderViewToString(this.ControllerContext, "AuctioneersList", previousAuctioneers) });
                else
                    return Json(new { previousLastId = -1, content = "" });
            }
            return null;
        }
        [HttpPost]
        public JsonResult  LoadNextAuctioneers(int auctionId,int startedId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            List<Auctioneer> nextAuctioneers = service.GetNNextAuctioneers(auctionId, startedId, 1, true).ToList();
            if (Request.IsAjaxRequest())
            {
                if (nextAuctioneers.Count > 0)
                    return Json(new { nextLastId = nextAuctioneers[0].AuctioneerId, content = Helper.RenderViewToString(this.ControllerContext, "AuctioneersList", nextAuctioneers) });
                else
                    return Json(new { nextLastId = -1, content="" });
            }
            return null;
        }
        [HttpPost]
        public JsonResult BidBuyAuction(int auctionId, string curUserAccName, DateTime postedDate,Decimal price)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            int state=-1;
            Auction auction = service.GetAuctionById(auctionId);
            if (auction == null)
                return Json(new { isOK = -1 });
            if (price <= service.GetHighestPrice(auctionId))
            {
                return Json(new { isOK = -3 });
            }
            if (auction.FinishedDate.CompareTo(DateTime.Now) <= 0)
            {
                return Json(new { isOK = -2 });//Het thoi gian dau gia
            }
            Auctioneer newAuctioneer = new Auctioneer() {AuctionId=auctionId,PostedDate=postedDate,Price=price,AuthorId=curUserAccName };
            state=service.AddNewAuctioneer(newAuctioneer);
            return Json(new { isOK = state  });
        }
        [HttpPost]
        public JsonResult GetHighestPrice(int auctionId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            decimal highestPrice = service.GetHighestPrice(auctionId);
            return Json(new { highestPrice = highestPrice });
        }
        #endregion
        #region Add new buy auctions
        [HttpPost]
        public string AddNewBuyAuction(FormCollection formCol,HttpPostedFileBase imageAddNewBuyAuctionInput)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            try
            {
                bool isOK = true;
                string message = "";

                string topic = formCol["topicAddNewBuyAuctionInputHidden"];
                if (topic.Trim() == "")
                {
                    message += "Chủ đề vẫn còn trống<br/>";
                    isOK = false;
                }

                DateTime startedDate;
                if (!DateTime.TryParse(formCol["startedDateAddNewBuyAuctionInputHidden"], out startedDate))
                {
                    message += "Thời điểm bắt đầu đấu giá không hợp lệ<br/>";
                    isOK = false;
                }
                if (startedDate < DateTime.Today.AddDays(1))
                {
                    message += "Thời điểm bắt đầu phải cách thời gian đăng ít nhất 1 ngày<br/>";
                    isOK = false;
                }
                DateTime finishedDate;
                if (!DateTime.TryParse(formCol["finishedDateAddNewBuyAuctionInputHidden"], out finishedDate))
                {
                    message += "Thời điểm kết thúc đấu giá không hợp lệ<br/>";
                    isOK = false;
                }

                decimal initialPrice ;
                if (!decimal.TryParse(formCol["initialPriceAddNewBuyAuctionInputHidden"], out initialPrice))
                {
                    message += "Giá khởi đầu không hợp lệ<br/>";
                    isOK = false;
                }

                Product product = (Product)serializer.Deserialize(formCol["productAddNewBuyAuctionSelectionHidden"], typeof(Product));

                string description = formCol["productDescriptionAddNewBuyAuctionInputHidden"];
                if (description.Trim() == "")
                {
                    message += "Chưa có nội dung mô tả<br/>";
                    isOK = false;
                }

                string userAccName = formCol["currUserAccNameInputHidden"];

                if (userAccName.Trim() == "") 
                {
                    message += "Thiếu thông tin người đăng bài<br/>";
                    isOK = false;
                }

                string imageFileName = "";

                byte[] imageBytes = null;

                
                if (imageAddNewBuyAuctionInput != null)
                {
                    imageBytes = new byte[imageAddNewBuyAuctionInput.ContentLength];
                    imageAddNewBuyAuctionInput.InputStream.Read(imageBytes, 0, imageAddNewBuyAuctionInput.ContentLength);
                    imageFileName = imageAddNewBuyAuctionInput.FileName;
                }
                else 
                {
                    string filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/TempProductImage.jpg");
                    FileInfo fileInfo = new FileInfo(filePath);

                    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                    BinaryReader binaryReader = new BinaryReader(fileStream);
                    imageBytes = binaryReader.ReadBytes((int)fileInfo.Length);
                    binaryReader.Close();

                    imageFileName="TempProductImage.jpg";
                }
                if(finishedDate.CompareTo(startedDate)<=0)
                {
                    message += "Thời gian bắt đầu phải sau thời gian kết thúc<br/>";
                    isOK = false;
                    
                }
                if(!isOK)
                    return serializer.Serialize(new { isOK = -1, Message = message });
                AgriMarketWebService service = new AgriMarketWebService();
                TypeOfAuction buyAuction = service.GetTypeOfAuctionById(1);
                Auction newBuyAuction = new Auction()
                {
                    Topic = topic,
                    PostedDate = DateTime.Now,
                    StartedDate = startedDate,
                    FinishedDate = finishedDate,
                    InitialPrice = initialPrice,
                    Product = product,
                    ProductDescription = description,
                    AuthorId = userAccName,
                    ProductImageBytes = imageBytes,
                    ProductImage = imageFileName,
                    Type = buyAuction
                };
                int state = service.AddNewAuction(newBuyAuction);
                if (state != -1)
                {
                    UserAccount userAccount = null;
                    if (Session["CurrentUserAccount"] != null)
                    {
                        userAccount = service.GetUserAccountByUserName(Session["CurrentUserAccount"].ToString());
                        ViewBag.CurrentUserAccount = userAccount;
                    }
                    newBuyAuction = service.GetAuctionById(state);
                    return serializer.Serialize(new { isOK = state, Message = "OK", Content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", new List<Auction>() { newBuyAuction}) });
                }
                return serializer.Serialize(new { isOK=state, Message="OK" });
            }
            catch
            {
                return serializer.Serialize(new { isOK = -1 , Message="Dữ liệu không hợp lệ" });
            }
        }
        #endregion
        #region SellAuction
        public ActionResult ViewSellAuctionIndex() 
        {
            AgriMarketWebService service = new AgriMarketWebService();
            CheckLogIn_NoRequire();
            List<Auction> newUnfinishedAuctions = service.GetNNewUnFinishedSellAuctions(2).ToList();
            ViewBag.NewUnfinishedAuctions = newUnfinishedAuctions;
            ViewBag.AllProducts = service.GetAllProducts().ToList();
            ViewBag.TypeId = 2;//sell auction
            ViewBag.TypeView = 1;//all auction
            return View("AuctionIndex");
        }
        [HttpPost]
        public string AddNewSellAuction(FormCollection formCol, HttpPostedFileBase imageAddNewSellAuctionInput)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            try
            {
                bool isOK = true;
                string message = "";

                string topic = formCol["topicAddNewSellAuctionInputHidden"];
                if (topic.Trim() == "")
                {
                    message += "Chủ đề vẫn còn trống<br/>";
                    isOK = false;
                }

                DateTime startedDate;
                if (!DateTime.TryParse(formCol["startedDateAddNewSellAuctionInputHidden"], out startedDate))
                {
                    message += "Thời điểm bắt đầu đấu giá không hợp lệ<br/>";
                    isOK = false;
                }
                if (startedDate < DateTime.Today.AddDays(1))
                {
                    message += "Thời điểm bắt đầu phải cách thời gian đăng ít nhất 1 ngày<br/>";
                    isOK = false;
                }
                DateTime finishedDate;
                if (!DateTime.TryParse(formCol["finishedDateAddNewSellAuctionInputHidden"], out finishedDate))
                {
                    message += "Thời điểm kết thúc đấu giá không hợp lệ<br/>";
                    isOK = false;
                }

                decimal initialPrice ;
                if (!decimal.TryParse(formCol["initialPriceAddNewSellAuctionInputHidden"], out initialPrice))
                {
                    message += "Giá khởi đầu không hợp lệ<br/>";
                    isOK = false;
                }

                Product product = (Product)serializer.Deserialize(formCol["productAddNewSellAuctionSelectionHidden"], typeof(Product));

                string description = formCol["productDescriptionAddNewSellAuctionInputHidden"];
                if (description.Trim() == "")
                {
                    message += "Chưa có nội dung mô tả<br/>";
                    isOK = false;
                }

                string userAccName = formCol["currUserAccNameInputHidden"];

                if (userAccName.Trim() == "") 
                {
                    message += "Thiếu thông tin người đăng bài<br/>";
                    isOK = false;
                }

                string imageFileName = "";

                byte[] imageBytes = null;

                
                if (imageAddNewSellAuctionInput != null)
                {
                    imageBytes = new byte[imageAddNewSellAuctionInput.ContentLength];
                    imageAddNewSellAuctionInput.InputStream.Read(imageBytes, 0, imageAddNewSellAuctionInput.ContentLength);
                    imageFileName = imageAddNewSellAuctionInput.FileName;
                }
                else 
                {
                    string filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/TempProductImage.jpg");
                    FileInfo fileInfo = new FileInfo(filePath);

                    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                    BinaryReader binaryReader = new BinaryReader(fileStream);
                    imageBytes = binaryReader.ReadBytes((int)fileInfo.Length);
                    binaryReader.Close();

                    imageFileName="TempProductImage.jpg";
                }
                if(finishedDate.CompareTo(startedDate)<=0)
                {
                    message += "Thời gian bắt đầu phải sau thời gian kết thúc<br/>";
                    isOK = false;
                    
                }
                if(!isOK)
                    return serializer.Serialize(new { isOK = -1, Message = message });
                AgriMarketWebService service = new AgriMarketWebService();
                TypeOfAuction sellAuction = service.GetTypeOfAuctionById(2);
                Auction newSellAuction = new Auction()
                {
                    Topic = topic,
                    PostedDate = DateTime.Now,
                    StartedDate = startedDate,
                    FinishedDate = finishedDate,
                    InitialPrice = initialPrice,
                    Product = product,
                    ProductDescription = description,
                    AuthorId = userAccName,
                    ProductImageBytes = imageBytes,
                    ProductImage = imageFileName,
                    Type = sellAuction
                };
                int state = service.AddNewAuction(newSellAuction);
                if (state != -1)
                {
                    CheckLogIn_NoRequire();
                    newSellAuction = service.GetAuctionById(state);
                    return serializer.Serialize(new { isOK = state, Message = "OK", Content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", new List<Auction>() { newSellAuction}) });
                }
                return serializer.Serialize(new { isOK=state, Message="OK" });
            }
            catch
            {
                return serializer.Serialize(new { isOK = -1 , Message="Dữ liệu không hợp lệ" });
            }
        }
        public ViewResult ViewSellAuction(Auction auction)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            CheckLogIn_NoRequire();
            ViewBag.AuctioneerList = service.GetNNNewAuctioneers(auction.AuctionId, 3).ToList();
            return View("AuctionView", auction);
        }

        #region Ajax
        [HttpPost]
        public ActionResult LoadNextSellAuctions(int startedId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            List<Auction> newUnfinishedSellAuctions = service.GetNUnfinishedSellAuctions(startedId, 1, true).ToList();
            CheckLogIn_NoRequire();
            if (Request.IsAjaxRequest())
            {
                if (newUnfinishedSellAuctions.Count > 0)
                    return Json(new { lastId = newUnfinishedSellAuctions[newUnfinishedSellAuctions.Count - 1].AuctionId, content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", newUnfinishedSellAuctions) });
                else
                    return Json(new { lastId = -1, content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", newUnfinishedSellAuctions) });
            }
            return PartialView("ListAuctionsView", newUnfinishedSellAuctions);
        }
        public JsonResult LoadNextSellAuctionAuctioneers(int auctionId, int startedId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            List<Auctioneer> nextAuctioneers = service.GetNNextAuctioneers(auctionId, startedId, 1, true).ToList();
            if (Request.IsAjaxRequest())
            {
                if (nextAuctioneers.Count > 0)
                    return Json(new { nextLastId = nextAuctioneers[0].AuctioneerId, content = Helper.RenderViewToString(this.ControllerContext, "AuctioneersList", nextAuctioneers) });
                else
                    return Json(new { nextLastId = -1, content="" });
            }
            return null;
        }
        [HttpPost]
        public JsonResult GetLowestPrice(int auctionId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            decimal lowestPrice = service.GetLowestPrice(auctionId);
            return Json(new { lowestPrice = lowestPrice });
        }
        [HttpPost]
        public JsonResult BidSellAuction(int auctionId, string curUserAccName, DateTime postedDate, Decimal price)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            int state = -1;
            Auction auction = service.GetAuctionById(auctionId);
            if (auction == null)
                return Json(new { isOK = -1 });
            if (price >= service.GetLowestPrice(auctionId))
            {
                return Json(new { isOK = -3 });
            }
            if (auction.FinishedDate.CompareTo(DateTime.Now) <= 0)
            {
                return Json(new { isOK = -2 });//Het thoi gian dau gia
            }
            Auctioneer newAuctioneer = new Auctioneer() { AuctionId = auctionId, PostedDate = postedDate, Price = price, AuthorId = curUserAccName };
            state = service.AddNewAuctioneer(newAuctioneer);
            return Json(new { isOK = state });
        }
        [HttpPost]
        public JsonResult LoadPreviousSellAuctionAuctioneers(int auctionId, int startedId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            List<Auctioneer> previousAuctioneers = service.GetNNextAuctioneers(auctionId, startedId, 3, false).ToList();
            if (Request.IsAjaxRequest())
            {
                if (previousAuctioneers.Count > 0)
                    return Json(new { previousLastId = previousAuctioneers[previousAuctioneers.Count - 1].AuctioneerId, content = Helper.RenderViewToString(this.ControllerContext, "AuctioneersList", previousAuctioneers) });
                else
                    return Json(new { previousLastId = -1, content = "" });
            }
            return null;
        }
        
        #endregion
        #endregion
        #region FollowedAuction
        [HttpPost]
        public JsonResult AddFollowedAuction(string curUserAccName, int auctionId) 
        {
            if (curUserAccName.Trim() != "")
            {
                AgriMarketWebService service = new AgriMarketWebService();
                int state=service.AddNewFollowedAuction(curUserAccName, auctionId);
                if (state >= 0)
                {
                    FollowedAuction followedAuction = service.GetAFollowedAuctionById(state);
                    return Json(new { isOK = state, Content = Helper.RenderViewToString(this.ControllerContext, "FollowedAuctionView", new List<FollowedAuction>() { followedAuction }) });
                }
                return Json(new { isOK=state});
            }
            else
            {
                return Json(new { isOK=-1 });
            }
        }
        public ViewResult ViewFollowedAuctions(string crrUserAccName) 
        {
            AgriMarketWebService service = new AgriMarketWebService();
            List<FollowedAuction> followedAuctions = service.GetFollowedAuctionsByUserAccName(crrUserAccName).ToList();
            return View("FollowedAuctionView", followedAuctions);
        }
        [HttpPost]
        public JsonResult DeleteFollowedAuction(int followedAuctionId) 
        {
            AgriMarketWebService service = new AgriMarketWebService();
            int state = service.DeleteFollowedAuction(followedAuctionId);
            return Json(new { isOK=state });
        }
        #endregion
        #region Search
        public ViewResult Search(string search_textbox) 
        {
            AgriMarketWebService service = new AgriMarketWebService();
            CheckLogIn_NoRequire();
            if (search_textbox.Trim() != "")
            {
               
                List<Auction> result = service.SearchForAuctions(search_textbox).ToList();
                return View("SearchAuctionView", result);
            }
            else
            {
                return View("SearchAuctionView", null);
            }
        }
        #endregion
        public ViewResult ViewAuctionDetails(int auctionId) 
        {
            AgriMarketWebService service = new AgriMarketWebService();
            CheckLogIn_NoRequire();
            Auction auction = service.GetAuctionById(auctionId);
            ViewBag.AllProducts = service.GetAllProducts().ToList();
            return View("AuctionDetailsView",auction);
        }
        public ViewResult BeingBuyAuctions()
        {
            AgriMarketWebService service = new AgriMarketWebService();
            CheckLogIn_NoRequire();
            List<Auction> beingBuyAuctions = service.GetNFirstBeingBuyAuctions(10).ToList();
            ViewBag.NewUnfinishedAuctions = beingBuyAuctions;
            ViewBag.AllProducts = service.GetAllProducts().ToList();
            ViewBag.TypeId = 1;//buy
            ViewBag.TypeView = 2;// being auction
            return View("AuctionIndex");
        }
        public ViewResult BeingSellAuctions()
        {
            AgriMarketWebService service = new AgriMarketWebService();
            CheckLogIn_NoRequire();
            List<Auction> beingSellAuctions = service.GetNFirstBeingSellAuctions(10).ToList();
            ViewBag.NewUnfinishedAuctions = beingSellAuctions;
            ViewBag.AllProducts = service.GetAllProducts().ToList();
            ViewBag.TypeId = 1;//buy
            ViewBag.TypeView = 2;// being auction
            return View("AuctionIndex");
        }
        [HttpPost]
        public ActionResult LoadNextBeingSellAuctions(int startedId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            List<Auction> beingSellAuctions = service.GetNNextBeingSellAuctions(startedId, 5, true).ToList();
            CheckLogIn_NoRequire();
            if (Request.IsAjaxRequest())
            {
                if (beingSellAuctions.Count > 0)
                    return Json(new { lastId = beingSellAuctions[beingSellAuctions.Count - 1].AuctionId, content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", beingSellAuctions) });
                else
                    return Json(new { lastId = -1, content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", beingSellAuctions) });
            }
            return PartialView("ListAuctionsView", beingSellAuctions);
        }
        [HttpPost]
        public ActionResult LoadNextBeingBuyAuctions(int startedId)
        {
            AgriMarketWebService service = new AgriMarketWebService();
            List<Auction> beingBuyAuctions = service.GetNNextBeingBuyAuctions(startedId, 5, true).ToList();
            CheckLogIn_NoRequire();
            if (Request.IsAjaxRequest())
            {
                if (beingBuyAuctions.Count > 0)
                    return Json(new { lastId = beingBuyAuctions[beingBuyAuctions.Count - 1].AuctionId, content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", beingBuyAuctions) });
                else
                    return Json(new { lastId = -1, content = Helper.RenderViewToString(this.ControllerContext, "ListAuctionsView", beingBuyAuctions) });
            }
            return PartialView("ListAuctionsView", beingBuyAuctions);
        }
    }
}
